<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\Plugin\ContactStage\Action\Dashboard;

use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\Utils\Codec\Json;
use MoChat\App\Common\Middleware\DashboardAuthMiddleware;
use MoChat\App\Rbac\Middleware\PermissionMiddleware;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\Request\ValidateSceneTrait;
use MoChat\Plugin\ContactStage\Contract\ContactStageContract;

/**
 * 客户阶段添加.
 *
 * Class Index.
 * @Controller
 */
class Store extends AbstractAction
{
    use ValidateSceneTrait;

    /**
     * @Inject
     * @var ContactStageContract
     */
    protected $contactStageService;

    /**
     * @Inject
     * @var StdoutLoggerInterface
     */
    protected $logger;

    /**
     * @RequestMapping(path="/dashboard/contactStage/store", methods="POST")
     * @Middlewares({
     *     @Middleware(DashboardAuthMiddleware::class),
     *     @Middleware(PermissionMiddleware::class)
     * })
     * @return array 返回数组
     */
    public function handle(): array
    {
        // 接收参数
        $params = [
            'name' => $this->request->input('name'),
            'description' => $this->request->input('description'),
        ];

        // 校验参数
        $this->validated($params);

        $user = user();

        $data = $this->contactStageService->getContactStageByCorpIdName($user['corpIds'][0], $params['name']);
        if ($data) {
            throw new CommonException(ErrorCode::INVALID_PARAMS, '已有该阶段名称，请勿重复添加');
        }

        // 数据处理
        $maxOrder = $this->contactStageService->getContactStageByCorpId($user['corpIds'][0]);
        $params['order'] = ! empty($maxOrder) ? $maxOrder['order'] + 1 : 1;
        $params['created_at'] = date('Y-m-d H:i:s');
        $params['corp_id'] = $user['corpIds'][0];
        $params['auto_attribute'] = Json::encode([]);
        $remindAttribute = [[
            'type' => 0,
            'status' => 0,
            'rule' => [],
        ],
            [
                'type' => 1,
                'status' => 0,
                'rule' => [],
            ],
        ];
        $params['remind_attribute'] = Json::encode($remindAttribute);

        // 数据操作
        Db::beginTransaction();
        try {
            // 创建活
            $res = $this->contactStageService->createContactStage($params);
            Db::commit();
        } catch (\Throwable $e) {
            Db::rollBack();
            $this->logger->error(sprintf('%s [%s] %s', '阶段创建失败', date('Y-m-d H:i:s'), $e->getMessage()));
            $this->logger->error($e->getTraceAsString());
            throw new CommonException(ErrorCode::SERVER_ERROR, $e->getMessage()); // '活动创建失败'
        }

        return [];
    }

    /**
     * 验证规则.
     *
     * @return array 响应数据
     */
    protected function rules(): array
    {
        return [
            'name' => 'required',
            'description' => 'required',
        ];
    }

    /**
     * 验证错误提示.
     * @return array 响应数据
     */
    protected function messages(): array
    {
        return [
            'name.required' => '阶段名称 必传',
            'description.required' => '描述 必传',
        ];
    }
}
